define(["jquery","bbcare","fu/app/comm/comm"],function($,$bb,$comm){
	var servers = {};
	var URL = $bb.baseUrl("followup");

	/**
	 * 获取上一个页面传递的参数
	 */
	servers.getPageParams = function(){
		return $bb.getPageParams().value;
	}

	/**
     * 患者方案内容查询
     */
    servers.ajaxDetail = function(params,indexStage,indexCourse,callback){
        $bb.ajax({
            url: URL + "followup/service/nutrition/patientscheme/detail",
            data: JSON.stringify({
                data: params
            }),
            success: function(data){
                if(data.success){
                    callback(data.data,params.ptSchemeId,params.phoneNo,indexStage,indexCourse);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "患者方案内容查询出错！");
                }
            }
        });
    };

    /**
     * 获取已启用的阶段名
     */
    servers.getUsedStage = function(list){
        for (var i = 0; i < list.length; i++) {
            if( list[i].status == "2"){
                return list[i];
            }   
        }
    }

    /**
     * 获取已启用的疗程名
     */
    servers.getUsedCourse = function(list){
        var usedStage, usedCourse;
        for (var i = 0; i < list.length; i++) {
            for (var j = 0; j < list[i].ptCourses.length; j++) {
                if( list[i].ptCourses[j].status == "2" ){
                    return list[i].ptCourses[j];
                }
            }
        }
    }

    /**
     * 根据当前页面的 疗程id 、阶段id 判断当前的阶段、疗程的状态（根据状态 按钮组按钮是否出现）
     * status：方案状态        1：正常  4：已终止
     * stageStatus： 阶段状态  1：正常  2：已启用  4：已终止
     * courseStatus：疗程状态  1：正常  2：已启用  4：已终止
     */
    servers.handleOperateSchemeBtnGroup = function(options){
        var data = {};
        var stageStatus,courseStatus;
        for (var i = 0; i < options.list.length; i++) {
            if( options.list[i].ptStageId == options.currStageId ){
                stageStatus = options.list[i].status;
            }
            for(var j = 0; j < options.list[i].ptCourses.length; j++){
                if( options.list[i].ptCourses[j].ptCourseId == options.currCourseId ){
                    courseStatus = options.list[i].ptCourses[j].status;
                }
            }
        }
        data = {
            "stageStatus":stageStatus,
            "courseStatus":courseStatus,
            "status":options.status
        }
        return data;
    }

    /**
     * 查询疗程详情
     */
    servers.ajaxCourseDetail = function(params,callback){
        $bb.ajax({
            url: URL + "followup/service/nutrition/patientCourseDetailForAllFood",
            data: JSON.stringify({
                data: params
            }),
            success: function(data){
                if(data.success){
                    callback(data.data);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "查询疗程详情出错！");
                }
            }
        });
    };

    /**
     * 将分钟转化为时间 eg: 250 ==> 4:10
     */
    var fillZero = function(s){
	    return s < 10 ? '0' + s: s;
	}
	var minuteChangeTime = function(minute){
		var hour = Math.floor(minute / 60);
		var min = fillZero(minute % 60);
		var result = hour + ":" + min;
		return result;
	}

    /**
     * 处理table heade里的数据
     */
    servers.handleCourseTableThead = function(data){
    	data.periodHeads.map(function(a){
			return a.foods.push({
				foodName: "其他",
				foodId:"other",
				periodName: a.periodName,
				periodId:a.periodId
			})
		})
    	for (var i = 0; i < data.periodHeads.length; i++) {
    		var startTime = minuteChangeTime(data.periodHeads[i].startTime);;
    		var endTime = minuteChangeTime(data.periodHeads[i].endTime);
    		data.periodHeads[i].time = startTime + "-" + endTime;
    		if( data.periodHeads[i].foods && data.periodHeads[i].foods.length == 0 ){
    			data.periodHeads[i].foods.push({});
    		}
    	}
    	if( data.courseNutritions && data.courseNutritions.length == 0 ){
    		data.courseNutritions.push({});
    	}
    	if( !data.courseNutritions ){
    		data.courseNutritions = [{}];
    	}
    	return data;
    }

    /**
     * 处理table tbody里的数据
     */
    servers.handleCourseTableTbody = function(data){
    	for (var i = 0; i < data.situations.length; i++) {
    		// 将situations里的foodList排好顺序，与periodHeads里的foods对应，
    		var arrFoodS = [];
			for (var p = 0; p < data.periodHeads.length; p++) {
				for (var q = 0; q < data.periodHeads[p].foods.length; q++) {
					if(data.periodHeads[p].foods[q].foodId == "other"){
						arrFoodS.push({
							data:data.situations[i].foodList.filter(function(a){if(a.isOther&&a.periodId==data.periodHeads[p].foods[q].periodId)return a}) ,
							dealState:4,
							flag:3
						});
					}else if( JSON.stringify(data.periodHeads[p].foods[q]) == "{}" ){
						arrFoodS.push({});
						break;
					}else{
						for (var j = 0; j < data.situations[i].foodList.length; j++) {
							if( data.situations[i].foodList[j].periodId == data.periodHeads[p].foods[q].periodId){
								if(data.situations[i].foodList[j].foodId == data.periodHeads[p].foods[q].foodId){
									arrFoodS.push(data.situations[i].foodList[j]);
									break;
								}
							}
	    				}
					}
    			}
    		}
    		data.situations[i].foodList = arrFoodS;
    		
    		
    		// dealState 登记状态: 用户录入、医生录入、未录入
    		for (var j = 0; j < data.situations[i].foodList.length; j++) {
    			if(data.situations[i].foodList[j].actualAmount < data.situations[i].foodList[j].defaultAmount){
    				data.situations[i].foodList[j].className = "intake-less";
    			}else if(data.situations[i].foodList[j].actualAmount > data.situations[i].foodList[j].defaultAmount){
    				data.situations[i].foodList[j].className = "intake-more";
    			}else{
    				data.situations[i].foodList[j].className = "intake-plan";
    			}
    			if(data.situations[i].foodList[j].dealState == "2"){ // 医生录入
    				data.situations[i].foodList[j].icoClassName = "fa-dot-circle-o";
    			}else if(data.situations[i].foodList[j].dealState == "3"){ // 用户录入
    				data.situations[i].foodList[j].icoClassName = "fa-circle-o";
    			}else if(data.situations[i].foodList[j].dealState == "4"){ // 用户录入
    				if(data.situations[i].foodList[j].data.length){
    					data.situations[i].foodList[j].icoClassName = "fa-sort-asc";
    				}
    				data.situations[i].foodList[j].dealState = 0;
    			}else{  // 未录入
    				data.situations[i].foodList[j].className = "intake-notReport";
    			}
    		}
    		
    		
            if(data.situations[i].nutrientList){
        		for (var j = 0; j < data.situations[i].nutrientList.length; j++) {
        			if( data.situations[i].nutrientList[j].actualAmount < data.situations[i].nutrientList[j].averageAmount ){
        				data.situations[i].nutrientList[j].className = "intake-less";
        			}else if( data.situations[i].nutrientList[j].actualAmount > data.situations[i].nutrientList[j].averageAmount ){
        				data.situations[i].nutrientList[j].className = "intake-more";
        			}else{
        				data.situations[i].nutrientList[j].className = "intake-plan";
        			}
        		}
            }
            
            
            if(data.situations[i].time){
                var time = new Date( data.situations[i].time );
                // "1":能修改实际饮食量和计划饮食量；"2":能修改计划饮食量；"0":不能修改
                if( data.stopTime == null || data.stopTime == "" ){
                    var currTime = new Date( $comm.getCurTime().date );
                    data.situations[i].flag = time <= currTime ? "1" : "2";
                }else{
                    var stopTime = new Date( data.stopTime );
                    data.situations[i].flag = time <= stopTime ? "1" : "0";
                }
            }else{
                data.situations[i].flag = false;
            }
    	}
    	return {
    		"situations":data.situations
    	};
    }

    /**
     * 营养疗程饮食量修改（包括计划饮食、实际饮食、饮食登记）
     */
    servers.ajaxAmountModify = function(params,callback,className){
        $bb.ajax({
            url: URL + "followup/service/nutrition/patientcourse/situation/modify",
            data: JSON.stringify({
                data: params
            }),
            success: function(data){
                if(data.success){
                    callback(params,className);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "营养疗程饮食量修改出错！");
                }
            }
        });
    };

    /**
     * 饮食量修改记录查询
     */
    servers.ajaxModifylist = function(situationId,callback){
        $bb.ajax({
            url: URL + "followup/service/nutrition/coursesituation/modifylist",
            data: JSON.stringify({
                data: {
                	"situationId":situationId
                }
            }),
            success: function(data){
                if(data.success){
                    callback(data.data);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "饮食量修改记录查询出错！");
                }
            }
        });
    };

    /**
     * 处理饮食量修改记录数据
     */
    servers.handleModifylist = function(list){
    	for (var i = 0; i < list.length; i++) {
    		if( list[i].type == "1" ){
    			list[i].actualAmount = "/";
    			list[i].tit = "修改计划值"
    		}else if( list[i].type == "2" ){
    			list[i].defaultAmount = "/";
    			list[i].tit = "医生修改实际值"
    		}else if(list[i].type == "3" ){
    			list[i].defaultAmount = "/";
    			list[i].tit = "用户修改实际值"
    		}
    	}
    	return {"list":list};
    }

    /**
     * 停止方案
     */
    servers.ajaxStopScheme = function(params,callback){
    	$bb.ajax({
            url: URL + "followup/service/nutrition/patientscheme/stop",
            data: JSON.stringify({
                data: {
                    "ptSchemeId":params.ptSchemeId,
                    "userId":params.userId
                }
            }),
            success: function(data){
                if(data.success){
                    callback(data,params);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "停止方案出错！");
                }
            }
        });
    }

    /**
     * 查询方案列表
     */
    servers.ajaxSchemeList = function(params,callback){
    	$bb.ajax({
            url: URL + "followup/service/nutrition/scheme/querylist",
            success: function(data){
                if(data.success){
                    callback(data.rows,params);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "查询方案列表出错！");
                }
            }
        });
    }

    /**
     * 更换方案
     */
    servers.ajaxChangeScheme = function(params,callback,className){
    	$bb.ajax({
            url: URL + "followup/service/nutrition/patientscheme/change",
            data: JSON.stringify({
                data: params
            }),
            success: function(data){
                if(data.success){
                	callback(data.data,className);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "更换方案出错！");
                }
            }
        });
    }

    /**
     * 启用阶段
     */
    servers.ajaxStartStage = function(params,callback){
        $bb.ajax({
            url: URL + "followup/service/nutrition/patientStage/used",
            data: JSON.stringify({
                data: {
                    "ptSchemeId":params.ptSchemeId,   
                    "ptStageId":params.ptStageId, 
                    "userId":params.userId,
                }
            }),
            success: function(data){
                if(data.success){
                    callback(data.data,params);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "启用该阶段出错！");
                }
            }
        });
    }

    /**
     * 启用疗程
     */
    servers.ajaxStartCourse = function(params,callback,className){
        $bb.ajax({
            url: URL + "followup/service/nutrition/patientcourse/startdayset",
            data: JSON.stringify({
                data: {
                    "ptSchemeId":params.ptSchemeId,   
                    "ptCourseId":params.ptCourseId, 
                    "startDate":params.startDate,
                }
            }),
            success: function(data){
                if(data.success){
                    callback(data,params,className);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "启用该疗程出错！");
                }
            }
        });
    }

    /**
     * 停用疗程
     */
    servers.ajaxStopCourse = function(params,callback){
        $bb.ajax({
            url: URL + "followup/service/nutrition/patientCourse/stop",
            data: JSON.stringify({
                data: {
                    "ptCourseId":params.ptCourseId
                }
            }),
            success: function(data){
                if(data.success){
                    callback(data.data,params);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "停用该疗程出错！");
                }
            }
        });
    }

    /**
     * 根据状态（阶段、疗程）
     */
    servers.getTipByStatus = function(status){
        var str;
        if(status == "1"){
            str = "未启用";
        }else if(status == "2"){
            str = "启用中";
        }else if(status == "4"){
            str = "已终止";
        }
        return str;
    }
    /**
     * 启用营养方案
     */
    servers.ajaxSchemeUsed = function(params,callback,className){
        $bb.ajax({
            url: URL + "followup/service/nutrition/patientscheme/used",
            data: JSON.stringify({
                data: params
            }),
            success: function(data){
                if(data.success){
                    callback(data.data,className);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "添加营养方案出错！");
                }
            }
        });
    }

	return servers;
});